<template>
  <div>
    <el-table :data="tableData" stripe style="width: 100%" v-loading="loading1" height="950px">
      <el-table-column prop="stime" label="时间" width="180">
        <template slot-scope="scope">{{
          scope.row.createTime | timestampToTime
        }}</template>
      </el-table-column>
      <el-table-column prop="beginAddress" label="起始地址" width="220">
      </el-table-column>
      <el-table-column prop="endAddress" label="终止地址" width="220">
      </el-table-column>
      <el-table-column prop="work" label="操作">
        <template slot-scope="scope">
          <el-button
            @click="lookOrders(scope.row)"
            size="mini"
            type="warning"
            >查看配送订单</el-button
          >
          <el-tag type="info" v-if="scope.row.status == 1">交易完成</el-tag>
          <el-button
            size="mini"
            type="success"
            @click="complete(scope.row.ordersList, scope.row.id)"
            v-if="scope.row.status == 0"
            >全部配送完成</el-button
          >
          <el-button
            size="mini"
            type="info"
            @click="lookPath(scope.row.pointsList)"
            >查看路径</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        :page-size="17"
        @current-change="currentChange"
        :current-page="$store.getters.getDistributionCurrent"
      >
      </el-pagination>
    </div>
    <el-drawer
      title="查看订单"
      :visible.sync="table"
      direction="rtl"
      size="80%"
      @closed="closed"
    >
      <el-table :data="gridData" v-loading="loading2">
        <el-table-column prop="stime1" label="时间" width="160">
          <template slot-scope="scope">{{
            scope.row.createTime | timestampToTime
          }}</template>
        </el-table-column>
        <el-table-column
          property="userName"
          label="姓名"
          width="80"
        ></el-table-column>
        <el-table-column
          property="phone"
          label="电话"
          width="120"
        ></el-table-column>
        <el-table-column
          property="goodsName"
          label="购买商品"
          width="140"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column label="购买数量" width="80">
          <template slot-scope="scope">
            <el-tag>{{ scope.row.num }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="交易金额" width="80">
          <template slot-scope="scope">
            <el-tag type="warning">￥{{ scope.row.money }}</el-tag>
          </template></el-table-column
        >
        <el-table-column
          property="address"
          label="地址"
          width="210"
        ></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-tag>{{ scope.row.methodPay | methodPayFilter }}</el-tag>
            <el-tag type="success" v-if="scope.row.orderStatus == 1"
              >配送中</el-tag
            >
            <el-tag type="info" v-if="scope.row.orderStatus == 2"
              >配送完成</el-tag
            >
            <el-button
              type="success"
              :disabled="scope.row.orderStatus != 1"
              size="mini"
              style="margin-left: 1%"
              @click="complete(scope.row.id, -1)"
              >配送完成</el-button
            >
            <el-button
              type="info"
              size="mini"
              @click="lookMap(scope.row.retailersId)"
              >查看地图</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-drawer
        title="查看地图"
        :append-to-body="true"
        :visible.sync="innerDrawer"
        size="50%"
        @opened="innerOpend"
      >
        <div id="innermap"></div>
      </el-drawer>
    </el-drawer>
    <el-drawer
      title="路径查询"
      :visible.sync="mapPath"
      direction="rtl"
      size="60%"
      @opened="opend"
    >
      <div id="mappath"></div>
    </el-drawer>
  </div>
</template>
 
<script>
import {
  getDistributionList,
  getOrderByIds,
  getOrderComplete,
  overOrder,
} from "@/api/orderApi";
import { getUserAddress } from "@/api/userApi";
export default {
  data() {
    return {
      table: false,
      dialog: false,
      loading1: true,
      loading2: true,
      innerDrawer: false,
      mapPath: false,
      tableData: [],
      gridData: [],
      p: [],
      userId: null,
      ordersList: null,
      tempId : -1,
      total : 0
    };
  },
  created() {
    this.init();
  },
  mounted() {
    // this.mapInit();
  },
  methods: {
    currentChange(current){
      this.$store.commit("setDistributionCurrent",current);
      this.loading1 = true
      this.init()
    },
    init() {
      getDistributionList(this.$store.getters.getDistributionCurrent).then((res) => {
        if (res.code == 0) {
          this.tableData = res.data.orderData;
          //console.log(res.data);
          this.total = res.data.size
          this.loading1 = false;
        } else {
          this.$message.error(res.message);
        }
      });
    },
    complete(data, status) {
      let ids = [].concat(data);
      this.$confirm(
        "请检查是否有线下货到付款的订单，仔细检查卖家金额是否不足",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          getOrderComplete(ids)
            .then((res) => {
              if (res.code == 0) {
                this.$message.success("成功");
                if (status == -1) {
                  getOrderByIds(this.ordersList).then((res) => {
                    
                    if (res.code == 0) {
                      //  console.log(res.data);
                      this.gridData = res.data;
                      let flag = true;
                      this.gridData.forEach((item) => {
                        if (item.orderStatus != 2) {
                          flag = false;
                        }
                      });
                      if (flag) {
                        overOrder(this.tempId).then((ires) => {
                          if (ires.code != 0) {
                            this.$message.error("更新列表错误");
                          }
                          this.init()
                        });
                      }
                    } else {
                      this.$message.error(res.message);
                    }
                  });
                } else {
                  overOrder(status).then((ires) => {
                    if (ires.code != 0) {
                      this.$message.error("更新列表错误");
                    }
                    this.init()
                  });
                }
                this.init();
              } else {
                this.$message.error(res.message);
              }
            })
            .catch((err) => {
              console.log(err);
            });
        })
        .catch(() => {});
    },
    closed() {
      this.loading2 = true;
    },
    innerOpend() {
      getUserAddress(this.userId).then((res) => {
        if (res.code == 0) {
          let map = new BMapGL.Map("innermap");
          map.enableScrollWheelZoom(true);
          let scaleCtrl = new BMapGL.ScaleControl(); // 添加比例尺控件
          let point = new BMapGL.Point(
            Number(res.data.pointLng),
            Number(res.data.pointLat)
          );
          let marker = new BMapGL.Marker(point);
          map.addControl(scaleCtrl);
          map.centerAndZoom(point, 19);
          map.addOverlay(marker);
        } else {
          this.$message.error(res.message);
        }
      });
    },
    opend() {
      let map = new BMapGL.Map("mappath");
      map.enableScrollWheelZoom(true);
      let scaleCtrl = new BMapGL.ScaleControl(); // 添加比例尺控件
      // map.centerAndZoom(_self.p[0], 15);
      // let driving = new BMapGL.DrivingRoute(map, {
      //   renderOptions: { map: map, autoViewport: true },
      // });
      let point = [];
      this.p.forEach((element) => {
        point.push(new BMapGL.Point(Number(element.lng), Number(element.lat)));
      });
      map.centerAndZoom(point[0], 15);
      map.addControl(scaleCtrl);
      var driving = new BMapGL.DrivingRoute(map, {
        renderOptions: { map: map, autoViewport: true },
      });
      driving.search(point[0], point[point.length - 1], {
        waypoints: point.slice(1, point.length - 1),
      });
    },
    lookOrders(data) {
      this.table = true;
      // console.log(data)
      this.ordersList = data.ordersList;
      this.tempId = data.id
      getOrderByIds(data.ordersList).then((res) => {
        if (res.code == 0) {
          //  console.log(res.data);
          this.gridData = res.data;
          this.loading2 = false;
        } else {
          this.$message.error(res.message);
        }
      });
    },
    lookMap(userId) {
      this.userId = userId;
      this.innerDrawer = true;
    },
    lookPath(pointList) {
      this.p = pointList;
      this.mapPath = true;

      //driving.search(_self.p[4], _self.p[0]);
    },
    mapInit() {
      // let _self = this;
      // let map = new BMapGL.Map("container");
      // let options = { renderOptions: {} };
      // let myLocalsearch = new BMapGL.LocalSearch(map, options);
      // map.enableScrollWheelZoom(true);
      // let scaleCtrl = new BMapGL.ScaleControl(); // 添加比例尺控件
      // map.addControl(scaleCtrl);
      // let mapPromise = new Promise((resolve, reject) => {
      //   _self.getPoint(myLocalsearch);
      //   myLocalsearch.setSearchCompleteCallback(function (searchResults) {
      //     // console.log(searchResults._pois[0].point.lat);
      //     if (typeof searchResults == "undefined") {
      //       alert("百度API没有搜索到该地址");
      //       return;
      //     }
      //     _self.p.push(searchResults._pois[0].point);
      //     _self.p1.push(searchResults._pois);
      //     if (_self.mapPoint.length == _self.p.length) {
      //       resolve("坐标解析成功");
      //     }
      //     // console.log(_self.p);
      //   });
      // });
      // mapPromise.then((res) => {
      //   map.centerAndZoom(_self.p[0], 15);
      //   let driving = new BMapGL.DrivingRoute(map, {
      //     renderOptions: { map: map, autoViewport: true },
      //   });
      //   console.log(this.p1);
      //   driving.search(_self.p[0], _self.p[1]); //waypoints表示途经点
      //   driving.search(_self.p[1], _self.p[2]);
      //   driving.search(_self.p[2], _self.p[3]);
      //   driving.search(_self.p[3], _self.p[4]);
      //   //driving.search(_self.p[4], _self.p[0]);
      // });
    },
  },
  filters: {
    timestampToTime(timestamp) {
      if (timestamp == null) {
        return "无";
      } else {
        var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
        var Y = date.getFullYear() + "-";
        var M =
          (date.getMonth() + 1 < 10
            ? "0" + (date.getMonth() + 1)
            : date.getMonth() + 1) + "-";
        var D =
          (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
        var h =
          (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) +
          ":";
        var m =
          (date.getMinutes() < 10
            ? "0" + date.getMinutes()
            : date.getMinutes()) + ":";
        var s =
          date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
        return Y + M + D + h + m + s;
      }
    },
    methodPayFilter(value) {
      if (value == 0) {
        return "线下货到结算";
      } else if (value == 1) {
        return "支付宝支付";
      } else {
        return "微信支付";
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.pagination {
  margin: 4% 0 0 0;
}
#innermap {
  width: 100%;
  height: 80%;
  //border: 1px solid b;
}
#mappath {
  width: 100%;
  height: 80%;
}
.about {
  position: relative;
  #container {
    width: 100%;
    height: 750px;
  }
  #panel {
    position: absolute;
    top: 1%;
    right: 0;
    width: 20%;
    overflow: scroll;
    height: 100%;
  }
}
</style>